import store from "@/store";
import global from "@/config/global.js";
import {
  getBackendData,
  isSuccessReqBackend,
  getBackendDataItems,
  getErrorMsgReqBackend,
} from "@/config/utils";
import gdToastService from "@uni_modules/gd-accbuild-core/components/gd-accbuild-ui/gd-ui/gd-service/gd-toast-service/gd-toast-service.js";
const isHttp = (path) => {
  return path.startsWith("http") || path.startsWith("https");
};
const getQueryString = (orgUrl, params) => {
  let paramsData = orgUrl.indexOf("?") === -1 ? "?" : "";
  Object.keys(params).forEach((key) => {
    if (Array.isArray(params[key])) {
      paramsData += `${params[key].map((el, index) => `ids=${el}`).join("&")}&`; //[${index}]
    } else {
      paramsData += `${key}=${
        params[key] !== null ? encodeURIComponent(params[key]) : ""
      }&`;
    }
  });
  return paramsData.substring(0, paramsData.length - 1);
};

const request = ({
  method,
  url,
  params = {},
  data = {},
  cloudFuncName,
  cloudFuncStrategyName,
  moduleCode,
  vmCode = null,
}) => {
  return new Promise(async (resolve, reject) => {
    if (global["enableServerless"]) {
      const res = await uniCloud.callFunction({
        name: cloudFuncName,
        data: {
          strategyName: cloudFuncStrategyName,
          moduleCode,
          vmCode,
          data,
          params,
          uniIdToken: uni.getStorageSync("uni_id_token"),
          uniIdTokenExpired: uni.getStorageSync("uni_id_token_expired"),
        },
      });
      //console.log(res, '结果======')
      if (res.result.errCode === 1002000006) {
        uni.redirectTo({
          url: "/uni_modules/gd-accbuild-core/pages/cross-platform/login/login",
        });
        return;
      }
      //在设计器中操作时，需要unicloud token权限的接口 token过期时,弹窗刷新token
      else if (
        res.result.errCode === -1002000006 &&
        cloudFuncName === "GdSysProject" &&
        cloudFuncStrategyName === "sendBizCrudHttpProxy"
      ) {
        const retRes = {
          code: res.result.errCode,
          msg: res.result.errMsg,
        };
        gdToastService({
          type: "error",
          message: getErrorMsgReqBackend(retRes),
        });
      }
      if (res.result.data.dbSchemaInfo) {
        uni.setStorageSync(
          "gdAccbuildUnicloudDbSchemaInfo",
          JSON.stringify(res.result.data.dbSchemaInfo)
        );
      }
      if (res.result.gdAccbuildUnicloudTokenInfo) {
        uni.setStorageSync(
          "gdAccbuildUnicloudTokenInfo",
          JSON.stringify(res.result.gdAccbuildUnicloudTokenInfo)
        );
      }
      if (res.result.gdAccbuildUnicloudSpaces) {
        uni.setStorageSync(
          "gdAccbuildUnicloudSpaces",
          JSON.stringify(res.result.gdAccbuildUnicloudSpaces)
        );
      }
      if (
        res.result.tokenInfo &&
        res.result.tokenInfo.token &&
        res.result.tokenInfo.tokenExpired
      ) {
        uni.setStorageSync("uni_id_token", res.result.tokenInfo.token);
        uni.setStorageSync(
          "uni_id_token_expired",
          res.result.tokenInfo.tokenExpired
        );
      }
      resolve({
        code: res.result.errCode,
        msg: res.result.errMsg,
        data: res.result.data,
        tokenInfo: res.result.tokenInfo,
        //items: res.result.items
      });
    } else {
      const queryString = getQueryString(url, params);
      uni
        .request({
          method,
          url: isHttp(url)
            ? url
            : `${global["BASE_URL"]}${global["BASE_API"]}${url}${queryString}`,
          header: {
            Authorization: store.state.token,
          },
          data,
        })
        .then((res) => {
          if (res.code === 200 || isSuccessReqBackend(res)) {
            resolve(res);
          } else {
            console.log("Failed", res.data.errors.message);
            gdToastService({
              message: res.data.errors.message,
              type: "error",
            });
            reject(res);
          }
        })
        .catch((err) => {
          reject(err);
          uni.showToast({
            title: err.message,
            icon: "none",
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    }
  });
};

export default request;
